package cn.gson.crm.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session=request.getSession();
		//判断用户是否登录
		if (session.getAttribute("user") == null) {
			//判断是否是ajax请求
			if("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
				//如果是ajax请求，则设置一个请求状态
				response.sendError(401);
			}else {
				//未登录，跳转到登录页面进行登录
				response.sendRedirect(request.getContextPath() + "/login");
			}
			return false;
		}
		return true;
	}
}
